package com.halden.TRPG.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.halden.TRPG.entity.RoomNicknameEntity;
import com.halden.TRPG.entity.vo.GetRoomMemberResponseMessageVo;
import com.halden.TRPG.entity.vo.GetRoomMembersResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
@ServerEndpoint("/websocket/{userId}/{rid}")
public class WebSocketServer {
    /**concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。*/
    private static ConcurrentHashMap<Long, ConcurrentHashMap<String, WebSocketServer>> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId = "";
    /**接收rId*/
    private Long rid = 0l;

    private static MessageService messageService;

    private static UserService userService;

    private static RoomNicknameService roomNicknameService;

    @Autowired
    public void setMessageService(MessageService messageService){
        WebSocketServer.messageService = messageService;
    }

    @Autowired
    public void  setUserService(UserService userService){
        WebSocketServer.userService = userService;
    }

    @Autowired
    public void setRoomNicknameService (RoomNicknameService roomNicknameService){
        WebSocketServer.roomNicknameService = roomNicknameService;
    }

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,
                       @PathParam("userId") String userId,
                       @PathParam("rid") Long rid) {
        this.session = session;
        this.userId=userId;
        this.rid = rid;
        if(!webSocketMap.containsKey(rid)){
            webSocketMap.put(rid,new ConcurrentHashMap<String,WebSocketServer>());
        }
        if (webSocketMap.get(rid).containsKey(userId)){
            webSocketMap.get(rid).remove(userId);
        }
        webSocketMap.get(rid).put(userId,this);
        log.info("用户:"+userId+"链接房间:"+rid+",当前房间人数为:" + getOnlineCount(rid));
        sendMembers();
    }

    /**
     * 连接关闭
     * 调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(rid)){
            webSocketMap.get(rid).remove(userId);
        }
        log.info("用户:"+userId+"退出房间:"+rid+"，当前房间人数" + getOnlineCount(rid));
        if (webSocketMap.get(rid).size() == 0){
            messageService.saveMessageWhenClose(rid);
        }
        sendMembers();
    }

    /**
     * 收到客户端消
     * 息后调用的方法
     * @param message
     * 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:"+userId+",报文:"+message);
        //可以群发消息
        //消息保存到数据库、redis
        if(StringUtils.hasLength(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("rid", this.rid);
//                log.info(jsonObject.toString());
//                log.info(messageService.toString());
                String msgType = jsonObject.getString("type");
                switch (msgType) {
                    case "message":
                        jsonObject.put("fromUserId", this.userId);
                        messageService.saveMessage(jsonObject);
                        break;
                    case "dice":
                        jsonObject.put("fromUserId", "dice");
                        messageService.saveMessage(jsonObject);
                        break;
                    case "diceHide":
                        jsonObject.put("fromUserId", "dice");
                        messageService.saveDarkDice(jsonObject);
                        jsonObject.put("message",jsonObject.getString("message4Other"));
                        jsonObject.put("type","dice");
                        jsonObject.remove("message4Other");
                        messageService.saveMessage(jsonObject);
                        break;
                    default:
                        break;
                }
                for (Map.Entry<String,WebSocketServer> entry : webSocketMap.get(rid).entrySet()){
                    if (entry.getKey().equals(this.userId)){
                        continue;
                    }
                    webSocketMap.get(rid).get(entry.getKey()).sendMessage(JSON.toJSONString(jsonObject));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务
     * 器主动推送
     */
    public void sendMessage(String message) {
        try{
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获得此时的
     * 在线人数
     * @return
     */
    public static synchronized int getOnlineCount(Long rid) {
        return webSocketMap.get(rid).size();
    }

    public void sendMembers() {
        List<GetRoomMembersResponseVo> vos = new ArrayList<>();
        for (Map.Entry<String,WebSocketServer> entry : webSocketMap.get(rid).entrySet()){
            GetRoomMembersResponseVo vo = new GetRoomMembersResponseVo();
            vo.setUid(entry.getKey());
            vo.setName(roomNicknameService.getNicknameString(rid, entry.getKey()));
            vo.setImg(String.valueOf(userService.getAvatar(entry.getKey()).getData()));
            vos.add(vo);
        }
        GetRoomMemberResponseMessageVo messageVo = new GetRoomMemberResponseMessageVo();
        messageVo.setMembers(vos);
        for (Map.Entry<String,WebSocketServer> entry : webSocketMap.get(rid).entrySet()){
            webSocketMap.get(rid).get(entry.getKey()).sendMessage(JSON.toJSONString(messageVo));
        }
    }
}